package events

import (
	"github.com/buger/jsonparser"
	"os"
	"security"
	"path/filepath"
	"fmt"
	"os/exec"
	"strconv"
)

func Push(bodySlc []byte, bodyLen int, signature string, workPath string)  {

	pid := os.Getpid()

	printLine("PUSH START PID:"+ strconv.Itoa(pid))
	projectName, err := jsonparser.GetString(bodySlc, "repository", "full_name")
	checkError(err)
	//ref branch
	ref, err2 := jsonparser.GetString(bodySlc, "ref")
	checkError(err2)
	//当前目录
	cwd, err3 := os.Getwd()
	checkError(err3)
	//工作目录长度
	wdl :=len([]rune(workPath))
	//当前文件所在目录
	realDir := string([]byte(cwd)[:wdl])
	//projectName eg: "empire/rbrm-pms-html"
	if projectName != "" && realDir == workPath {
		projectDir := getProjectDir(projectName)
		realBody := string(bodySlc[:bodyLen])
		//检查秘钥
		isOk, msg := security.CheckSignature(signature, realBody, projectDir)
		if !isOk {
			printLine(msg)
			printLine("终止")
			return
		}
		branchName := filepath.Base(ref)
		printBeforWithSpaceLine("分支:" + branchName)
		var command = filepath.Join(projectDir, branchName+"-push.sh")
		//检查文件
		if fileExist(command) {
			printBeforWithSpaceLine("名称:" + command)
			//获取执行文件绝对路径
			commandAbsPath, _:= filepath.Abs(command)
			printBeforWithSpaceLine(`服务器路径:` + commandAbsPath)
			printBeforWithSpaceLine(`工作目录:` + workPath)
			commandFileDir := string([]byte(commandAbsPath)[:wdl])
			if commandFileDir != workPath {
				fmt.Printf("执行文件目录: %s, 不在工作目录: %s中\n", commandAbsPath, workPath )
			} else {
				cmd := exec.Command("/bin/bash", "-c", commandAbsPath)
				output, err := cmd.Output()
				if err != nil {
					fmt.Printf("Execute Shell:%s failed with error:%s", commandAbsPath, err.Error())
				} else {
					fmt.Printf("执行脚本 :%s 完成  输出:\n%s", command, string(output))
				}
			}
		} else {
			printBeforWithSpaceLine( command + " 未找到 执行文件")
		}
	}
	printLine("PUSH 请求 FINISH:" +  strconv.Itoa(pid))
}



